<template>
    <!--    供应商基本信息-->
    <div class="suppliers-container">
        <h1>供应商基本信息</h1>

        <div v-if="loading" class="loading">加载中...</div>

        <div v-else>
            <div class="action-buttons">
                <button v-if="!isEditing" @click="startEditing" class="edit-btn">编辑</button>
                <button v-if="isEditing" @click="saveChanges" class="save-btn">保存</button>
                <button v-if="isEditing" @click="cancelEditing" class="cancel-btn">取消</button>
            </div>


            <form @submit.prevent="saveChanges" :module="form" class="suppliers-form">
                <div class="form-group">
                    <label>供应商编号:</label>
                    <span v-if="!isEditing">{{ form.suppliers.supplierId }}</span>
                    <input v-else v-model="editablesuppliers.supplierId" type="text" disabled>
                </div>

                <div class="form-group">
                    <label>供应商名称:</label>
                    <span v-if="!isEditing">{{ form.suppliers.name }}</span>
                    <input v-else v-model="editablesuppliers.name" type="text" required>
                </div>

                <div class="form-group">
                    <label>联系人:</label>
                    <span v-if="!isEditing">{{ form.suppliers.contactName }}</span>
                    <input v-else v-model="editablesuppliers.contactName" type="text">
                </div>

                <div class="form-group">
                    <label>联系电话:</label>
                    <span v-if="!isEditing">{{ form.suppliers.contactPhone }}</span>
                    <input v-else v-model="editablesuppliers.contactPhone" type="tel" required>
                </div>

                <div class="form-group">
                    <label>地址:</label>
                    <template v-if="!isEditing">
                        <span>{{ formatAddress(form.suppliers.address) }}{{ form.suppliers.addressDetail ? '/' + form.suppliers.addressDetail : '' }}</span>
                    </template>
                    <template v-else>
                        <div class="address-edit-container">
                            <el-cascader
                                v-model="editablesuppliers.address"
                                :options="regionData"
                                :props="{
                                  expandTrigger: 'hover',
                                  value: 'value',
                                  label: 'label',
                                  children: 'children'
                                 }"
                                clearable
                                filterable
                                placeholder="请选择省市区"
                                class="address-cascader">
                            </el-cascader>
                            <el-input
                                v-if="isEditing"
                                v-model="editablesuppliers.addressDetail"
                                placeholder="请输入详细地址（街道、门牌号等）"
                                clearable
                                class="address-detail-input">
                            </el-input>
                        </div>
                    </template>
                </div>

                <div class="form-group">
                    <label>营业执照:</label>
                    <el-upload
                        v-if="isEditing"
                        class="license-uploader"
                        name="photo"
                        action="http://localhost:8888/product/upload"
                        :show-file-list="false"
                        :on-success="handleYYZZSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="form.suppliers.license" :src="form.suppliers.license" class="license-image">
                        <div v-else class="uploader-placeholder">
                            <i class="el-icon-plus"></i>
                            <div class="uploader-text">上传营业执照</div>
                        </div>
                    </el-upload>
                    <span v-if="!isEditing"><img :src="form.suppliers.license" alt="供应商营业执照"></span>
                </div>

                <div class="form-group">
                    <label>Logo:</label>
                    <el-upload
                        v-if="isEditing"
                        class="logo-uploader"
                        name="photo"
                        action="http://localhost:8888/product/upload"
                        :show-file-list="false"
                        :on-success="handleLogoSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="form.suppliers.logo" :src="form.suppliers.logo" class="logo-image">
                        <div v-else class="uploader-placeholder">
                            <i class="el-icon-plus"></i>
                            <div class="uploader-text">上传Logo</div>
                        </div>
                    </el-upload>
                    <span v-if="!isEditing"><img :src="form.suppliers.logo" alt="供应商Logo"></span>
                </div>


                <div class="form-group">
                    <label>营业状态:</label>
                    <span v-if="!isEditing">{{ form.suppliers.isBusiness === 0 ? '营业中' : '暂停营业' }}</span>
                    <el-select v-else v-model="editablesuppliers.isBusiness" class="status-select">
                        <el-option label="营业中" :value="0"></el-option>
                        <el-option label="暂停营业" :value="1"></el-option>
                    </el-select>
                </div>
                <div class="form-group">
                    <label>账户余额:</label>
                    <span v-if="!isEditing">{{ form.suppliers.balance }}</span>
                    <input v-else v-model="editablesuppliers.balance" type="text" disabled readonly>
                </div>
            </form>
        </div>
    </div>
</template>

<script>
import {regionData,  codeToText} from 'element-china-area-data'
import moment from "moment/moment";
export default {
    name: 'suppliersInfo',
    data() {
        return {
            regionData: regionData,
            CodeToText: codeToText, // 将 CodeToText 存入 data 中


            form: {},
            loading: true,
            isEditing: false,
            editablesuppliers: {
                name: '',
                contactName: '',
                contactPhone: '',
                license: '',
                logo: '',
                address: [],
                addressDetail: '',
                updatedAt:moment().format('YYYY-MM-DD HH:mm:ss'),
            },//编辑
        }
    },
    methods: {
        // 格式化地址方法
        formatAddress(codes) {
            if (!codes || !this.CodeToText) return '未设置地址'

            try {
                const codeArray = typeof codes === 'string' ? codes.split(',') : codes
                return codeArray
                    .map(code => {
                        // 确保 code 存在且 CodeToText 中有对应的值
                        return code && this.CodeToText[code] ? this.CodeToText[code] : ''
                    })
                    .filter(text => text) // 过滤掉空值
                    .join('')
            } catch (error) {
                console.error('地址格式化错误:', error)
                return codes // 如果出错，返回原始值
            }
        },
        //获取供应商信息
        searchSuppliersOne() {
            this.loading = true // 先显示加载状态
            let user = JSON.parse(sessionStorage.getItem('user'))
            console.log(888,user)
            this.$axios.post(`login/selectIdSuppliers/${user.id}`).then(r => {
                this.form=r.data
                this.loading = false // 加载完成后隐藏加载状态
            })
        },
        //编辑供应商信息
        startEditing() {
            this.editablesuppliers = {
                ...this.form.suppliers,
                // 确保地址是数组格式
                address: this.form.suppliers.address ?
                    (Array.isArray(this.form.suppliers.address) ?
                        this.form.suppliers.address :
                        this.form.suppliers.address.split(',')) :
                    [],
                // 初始化详细地址
                addressDetail: this.form.suppliers.addressDetail || ''
            }
            this.isEditing = true
        },
        //保存供应商信息
        saveChanges() {
            // 表单验证
            if (!this.editablesuppliers.name || !this.editablesuppliers.contactPhone) {
                this.$message.error('供应商名称和联系电话不能为空')
                return
            }

            // 准备要保存的数据 - 将地址数组转换为字符串
            const dataToSave = {
                ...this.editablesuppliers,
                address: Array.isArray(this.editablesuppliers.address) ?
                    this.editablesuppliers.address.join(',') :
                    this.editablesuppliers.address
            }

            this.loading = true
            this.$axios.put(`suppliers/updateSupplier`, dataToSave)  // 使用转换后的数据
                .then(response => {
                    this.form.suppliers = response.data
                    this.isEditing = false
                    this.loading = false
                    this.$message.success('供应商信息已更新')
                    this.searchSuppliersOne()
                })
                .catch(error => {
                    console.error('保存失败:', error)
                    this.loading = false
                    this.$message.error('保存失败: ' + error.message)
                })
        },
        // Logo 营业执照上传前处理
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        // Logo 营业执照上传成功处理
        handleYYZZSuccess(res, file) {
            this.editablesuppliers.license = URL.createObjectURL(file.raw);
        },
        //  营业执照上传成功处理
        handleLogoSuccess(res, file) {
            this.editablesuppliers.logo = URL.createObjectURL(file.raw);
        },
        //取消编辑
        cancelEditing() {
            this.isEditing = false
        },

    },
    created() {
        this.searchSuppliersOne()
    },
}
</script>

<style scoped>

.suppliers-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 30px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.form-group img {
    max-width: 100%;
    max-height: 200px;
    display: block;
    margin: 10px auto;
    border-radius: 4px;
    object-fit: contain;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h1 {
    color: #333;
    text-align: center;
    margin-bottom: 30px;
    font-size: 28px;
    font-weight: 600;
}

.loading {
    text-align: center;
    padding: 50px;
    font-size: 18px;
    color: #666;
}

.action-buttons {
    text-align: right;
    margin-bottom: 20px;
}

button {
    padding: 10px 20px;
    margin-left: 10px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;
}

button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.edit-btn {
    background-color: #409EFF;
    color: white;
}

.save-btn {
    background-color: #67C23A;
    color: white;
}

.cancel-btn {
    background-color: #909399;
    color: white;
}

.suppliers-form {
    background-color: white;
    padding: 20px;
    border-radius: 6px;
}

.form-group {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.form-group label {
    width: 120px;
    font-weight: bold;
    color: #555;
}

.form-group span {
    flex: 1;
    padding: 8px;
    background-color: #f5f5f5;
    border-radius: 4px;
}

.form-group input,
.form-group select,
.form-group textarea {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.form-group textarea {
    min-height: 80px;
    resize: vertical;
}

@media (max-width: 600px) {
    .form-group {
        flex-direction: column;
        align-items: flex-start;
    }

    .form-group label {
        width: 100%;
        margin-bottom: 5px;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
        width: 100%;
    }

}
.address-edit-container {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.address-cascader {
    margin-bottom: 10px;
    width: 100%;
}

.address-detail-input {
    width: 100%;
}
</style>